<template>
  <div class="logo" style="margin:0 auto; width: 600px; margin-top: 100px; text-align: center">
    <img src="../assets/logo.png" alt="" style="width: auto; height: auto; margin-left: 20px;">
  </div>
  <div class="register">
    <h1 style="text-align: center;">用户名密码注册</h1>
    <el-form :model="user" label-width="auto" style="width: 300px; padding-left: 150px; ">
      <el-form-item >
        <el-input v-model="user.username" placeholder="用户名" />
      </el-form-item>
      <el-form-item >
        <el-input v-model="user.password" placeholder="密码" />
      </el-form-item>
      <el-form-item >
        <el-input v-model="user.re_password" placeholder="重复密码" />
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="register">注册</el-button>
    <el-button type="primary" @click="router.push('/')">已有账号？点击登录</el-button><br><br>
    <el-button type="primary" @click="router.push('/sms_register')">使用手机号注册</el-button>
  </div>
  
</template>

<style scoped>
  .register{
    width: 600px;
    height: 400px;
    margin: 0 auto;
    text-align: center;
    border: 2px solid black;
    border-radius: 10px;
    
  }
</style>

<script setup>
  import { ref, onMounted } from "vue"
  import axios from "axios"
  import { useRoute, useRouter } from "vue-router";

  const route = useRoute()
  const router = useRouter()

  let user = ref({
    "username": "",
    "password": "",
    "re_password": "",
  })

  const register=()=>{
    if(user.value.username === ""){
        alert("用户名不能为空")
      }
    else if(user.value.password === ""){
      alert("密码不能为空")
    }
    else if(user.value.password !== user.value.re_password){
      alert("两次密码输入不同")
    }
    else{
      axios.post(`http://127.0.0.1:8000/user/register/`, user.value)
      .then(res=>{
        console.log(res)
        localStorage.setItem("access_token", res.data.token)
        localStorage.setItem("refresh_token", res.data.refresh)
        router.push("/homepage")
      })
      .catch(error=>{
        console.log(error)
        if("username" in error.response.data && error.response.data.username[0] === "A user with that username already exists."){
          alert("该用户名已注册")
        }
      })
    }
  }
</script>
